package com.eques.demo

import android.os.Bundle
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eques.base.BaseActivity
import com.eques.bean.AlarmRecord
import com.eques.demo.adapter.AlarmRecordAdapter
import com.eques.util.Config
import com.eques.util.DateTimeUtil
import com.eques.util.HttpUtil
import org.json.JSONObject

class AlarmRecordListActivity : BaseActivity() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: AlarmRecordAdapter
    private lateinit var tvEmpty: TextView
    private lateinit var tvTotal: TextView
    private var devId: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_alarm_record_list)
        devId = intent.getStringExtra("devId").toString()
        initView()
    }

    override fun initView() {
        initViews()
        setupRecyclerView()
        loadData()
    }

    override fun initData() {
    }

    private fun initViews() {
        recyclerView = findViewById(R.id.recyclerView)
        tvEmpty = findViewById(R.id.tv_empty)
        tvTotal = findViewById(R.id.tv_total)

        // 设置标题
        findViewById<TextView>(R.id.tv_title).text = "报警记录"
    }

    private fun setupRecyclerView() {
        adapter = AlarmRecordAdapter()
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter

        // 设置点击监听
        adapter.onItemClickListener = { record ->
            showAlarmDetail(record)
        }
    }

    private fun loadData() {
        var startAndEndDate = DateTimeUtil.getCurrDate()
        var startTime = java.lang.String.valueOf(
            DateTimeUtil.getSpecifiedDateTime_000000(startAndEndDate).time
        )
        var endTime = java.lang.String.valueOf(
            DateTimeUtil.getSpecifiedDateTime_235959(startAndEndDate).time
        )
        var host = preference.getSubUrl()
        val token = preference.getString(Config.EQUES_USER_TOKEN)
        val uid = preference.getString(Config.EQUES_USER_UID)
        val url = Config.getE1ProOpenLockAlarmListUrl(
            host,
            uid,
            token,
            devId,
            startTime,
            endTime,
            "0",
            "1000"
        )
        println("GET Alarm url: $url")
        HttpUtil.getAsync(
            url = url.toString(),
        ) { result ->
            result.onSuccess { response ->
                println("GET Alarm Response: $response")
                runOnUiThread {
                    parseAndDisplayData(response)
                }

            }.onFailure { exception ->
                println("GET Error: ${exception.message}")
            }
        }


    }

    private fun parseAndDisplayData(jsonString: String) {
        try {
            val jsonObject = JSONObject(jsonString)
            val listArray = jsonObject.getJSONArray("list")
            val total = jsonObject.getInt("total")
            val records = mutableListOf<AlarmRecord>()

            for (i in 0 until listArray.length()) {
                val item = listArray.getJSONObject(i)
                val record = AlarmRecord(
                    fid = item.getString("fid"),
                    create_time = item.getLong("create_time"),
                    alarm = item.getInt("alarm"),
                    lock_aid = item.getString("lock_aid"),
                    pid = item.getString("pid"),
                    time = item.getLong("time"),
                    category = item.getInt("category"),
                    lock_id = item.getString("lock_id")
                )
                records.add(record)
            }

            adapter.setData(records)

            // 显示总数
            tvTotal.text = "共 $total 条报警记录"

            // 显示/隐藏空状态
            if (records.isEmpty()) {
                tvEmpty.visibility = TextView.VISIBLE
                recyclerView.visibility = RecyclerView.GONE
                tvTotal.visibility = TextView.GONE
            } else {
                tvEmpty.visibility = TextView.GONE
                recyclerView.visibility = RecyclerView.VISIBLE
                tvTotal.visibility = TextView.VISIBLE
            }

        } catch (e: Exception) {
            e.printStackTrace()
            tvEmpty.text = "数据加载失败"
            tvEmpty.visibility = TextView.VISIBLE
            recyclerView.visibility = RecyclerView.GONE
            tvTotal.visibility = TextView.GONE
        }
    }

    private fun showAlarmDetail(record: AlarmRecord) {
        // 跳转到详情页面或显示详情对话框
        // 这里可以显示更详细的报警信息
        android.widget.Toast.makeText(
            this,
            "${record.getAlarmType()} - ${record.getDetailTime()}",
            android.widget.Toast.LENGTH_SHORT
        ).show()
    }
}